/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.osdtsystem.utils;

import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;

/**
 * A class that acts as list wrapper of an int[] array, providing the functionality
 * for arrays of integers that ArrayList provides for arrays of Objects.
 * @author Matthias Buch-Kromann
 */
public class IntList extends AbstractList<Integer> {
    int length = 0;
    int[] array;

    public IntList() {
        array = new int[4];
    }

    public IntList(List<Integer> list) {
        length = list.size();
        array = new int[length];
        for (int i = 0; i < length; ++i) {
            array[i] = list.get(i);
        }
    }
    
    public IntList(final int[] array) {
        this.length = array.length;
        this.array = array;
    }

    @Override
    public Integer get(int index) {
        if (index < 0 || index >= length)
            throw new ArrayIndexOutOfBoundsException(index);
        return array[index];
    }

    @Override
    public int size() {
        return length;
    }

    @Override
    public Integer set(int index, Integer element) {
        int oldvalue = array[index];
        array[index] = element;
        return oldvalue;
    }

    @Override
    public void add(int index, Integer element) {
        // Grow array by factor 1.5 if array is full
        if (length == array.length) {
            array = Arrays.copyOf(array, (int) (length * 1.5 + 1));
        }

        // Check index
        if (index < 0 || index > length)
            throw new ArrayIndexOutOfBoundsException(index);

        // Move all tail elements to the right, if applicable
        if (index != size()) {
            for (int i = length - 1; i >= index; --i) {
                array[i+1] = array[i];
            }
        }

        // Add new element
        array[index] = element;
        ++length;
    }

    @Override
    public Integer remove(int index) {
        if (index < 0 || index >= length)
            throw new ArrayIndexOutOfBoundsException(index);

        // Move all tail elements one down
        int removed = array[index];
        for (int i = index; i < length - 1; ++i) {
            array[i] = array[i+1];
        }

        // Return removed integer
        --length;
        return removed;
    }

    public void trimToSize() {
        array = Arrays.copyOf(array, length);
    }
}
